<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>鼠标事件实现拖拽</title>
  <style>
    * {
      padding: 0;
      margin: 0;
      box-sizing: border-box;
    }

    body {
      position: relative;
    }

    .box {
      position: absolute;
      width: 25vw;
      height: 25vw;
      background-color: lightcoral;
      top: 50px;
      left: 100px;
    }
  </style>
</head>

<body>
  <!-- 
  mousedown 鼠标按下
  mousemove 鼠标移动
  mouseup 鼠标松开 
  -->


  <div class="box">
  </div>

  <script>
    const box = document.querySelector('.box')
    let innerX = 0
    let innerY = 0
    box.addEventListener('mousedown', (e) => {
      console.log(e.pageX, e.offsetX);
      innerX = e.offsetX
      innerY = e.offsetY

      document.addEventListener('mousemove', mouse)



      document.addEventListener('mouseup', (e) => {
        document.removeEventListener('mousemove', mouse)
      })

    }, false)


    function mouse(e) {
      // 获取鼠标距离页面上的坐标
      const mouse2PageX = e.pageX
      const mouse2PageY = e.pageY
      // 计算方块的left和top 从而实现元素的移动
      box.style.left = mouse2PageX - innerX > 0 ? mouse2PageX - innerX + 'px' : 0
      box.style.top = mouse2PageY - innerY > 0 ? mouse2PageY - innerY + 'px' : 0
    }
  </script>
</body>

</html>